let movableAreaWidth = 0
let movableViewWidth = 0
const backgroundAudioManager = wx.getBackgroundAudioManager()
let preSec = -1 // 上一个的秒数
let duration = 0 // 当前歌曲的总时长，以秒为单位的

// 解决当进度条拖动时候和updatetime事件有冲突的问题
let isDrag = false // 进度条是否拖拽标志为

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    showTime: {
      currentTime: '00:00',
      totalTime: '00:00'
    },
    movableDis: 0,
    progress: 0
  },

  // 组件生命周期函数写在 lifetimes 对象里，当组件在页面布局完成时会调用生命周期函数
  lifetimes: {
    ready() {
      this._getMovableDis()
      this._bindBGMEvent()
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onChange(event) {
      // console.log(event)
      // 拖动
      if (event.detail.source == 'touch') {
        this.data.progress = event.detail.x / (movableAreaWidth - movableViewWidth) * 100
        this.data.movableDis = event.detail.x
        isDrag = true
        console.log(isDrag)
      }
    },
    onTouchEnd() {
      backgroundAudioManager.seek(duration * this.data.progress / 100)
      const currentTimeFmt = this._dateFormat(duration * this.data.progress / 100)
      isDrag = false
      console.log(isDrag)
      this.setData({
        progress: this.data.progress,
        movableDis: this.data.movableDis,
        ['showTime.currentTime']: currentTimeFmt.min + ':' + currentTimeFmt.sec
      })
    },
    _getMovableDis() {
      const query = this.createSelectorQuery()
      query.select('.movable_area').boundingClientRect()
      query.select('.movable_view').boundingClientRect()
      query.exec((rect) => {
        console.log(rect)
        movableAreaWidth = rect[0].width
        movableViewWidth = rect[1].width
      })
    },
    _bindBGMEvent() {
      backgroundAudioManager.onPlay(() => {
        console.log('onPlay')
        isDrag = false
      })

      backgroundAudioManager.onStop(() => {
        console.group('onStop')
      })

      backgroundAudioManager.onPause(() => {
        console.group('Pause')
      })

      backgroundAudioManager.onWaiting(() => {
        console.log('onWaiting')
      })

      backgroundAudioManager.onCanplay(() => {
        console.log(backgroundAudioManager.duration)
        if (typeof backgroundAudioManager.duration != 'undefined') {
          this._setTime()
        } else {
          setTimeout(() => {
            this._setTime()
          }, 1000)
        }
      })

      // 进度变化时触发
      backgroundAudioManager.onTimeUpdate(() => {
        if (!isDrag) {
          const currentTime = backgroundAudioManager.currentTime
          const duration = backgroundAudioManager.duration
          // 获取当前时间的秒数
          const currentSec = currentTime.toString().split('.')[0]
          // 当前时间秒数不等于上一个时间的秒数时更新数据
          if (preSec != currentSec) {
            // console.log(currentTime)
            const currentTimeFmt = this._dateFormat(currentTime)
            this.setData({
              movableDis: (movableAreaWidth - movableViewWidth) * currentTime / duration,
              progress: currentTime / duration * 100,
              ['showTime.currentTime']: `${currentTimeFmt.min}:${currentTimeFmt.sec}`
            })
            preSec = currentSec
            // 联动歌词
            this.triggerEvent('timeUpdate', {
              currentTime
            })
          }
        }
      })

      backgroundAudioManager.onEnded(() => {
        console.log('onEnded')
        this.triggerEvent('musicEnd')
      })

      backgroundAudioManager.onError((res) => {
        console.error(res.errMsg)
        console.error(res.errCode)
        wx.showToast({
          title: '错误：' + res.errCode
        })
      })
    },

    _setTime() {
      duration = backgroundAudioManager.duration
      // console.log(duration)
      const durationFmt = this._dateFormat(duration)
      this.setData({
        ['showTime.totalTime']: `${durationFmt.min}:${durationFmt.sec}`
      })
    },

    // 格式化时间
    _dateFormat(sec) {
      const min = Math.floor(sec / 60)
      sec = Math.floor(sec % 60)
      return {
        'min': this._parse0(min),
        'sec': this._parse0(sec)
      }
    },

    // 补零
    _parse0(num) {
      return num < 10 ? '0' + num : num
    }
  }
})